﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Keepo.Models;
using Infrastructure.Data;

namespace Keepo.Helpers
{
    //this GlobalFilter Attribute will load the RememberMe Cookies on every Request
    public class LoadRememberMeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            var Session = filterContext.HttpContext.Session;

            if (!UserHelper.IsLogon())
            {
                using (GenericRepository repository = new GenericRepository())
                {
                    //LOAD USER SETTINGS FROM REMEMBER ME COOKIES
                    var Request = filterContext.HttpContext.Request;

                    if (Request.Cookies["email"] != null && Request.Cookies["password"] != null)
                    {
                        //check if the user selected "RememberMe" and then his email and password been saved in the cookie
                        if (!String.IsNullOrEmpty(Request.Cookies["email"].Value) && !String.IsNullOrEmpty(Request.Cookies["password"].Value))
                        {
                            string email = Request.Cookies["email"].Value;
                            string password = Request.Cookies["password"].Value;

                            email = StringHelper.FromGibrishToHebrew(email);
                            password = StringHelper.FromGibrishToHebrew(password);
                            password = StringHelper.Decrypt(password);

                            //search user with this email and password
                            var existUser = repository.First<User>(m => m.Email == email && m.Password == password);

                            //found user with this email and password
                            if (existUser != null)
                            {
                                if (Session != null)
                                {
                                    //create session
                                    Session["user"] = existUser;
                                    Session.Timeout = 60;

                                    //add 2 more days to the expiry of the cookies
                                    Request.Cookies["email"].Expires = DateTime.Now.AddDays(2);
                                    Request.Cookies["password"].Expires = DateTime.Now.AddDays(2);
                                }
                            }
                        }
                    }
                }
            }
            
        }
    }
}